import config from '../../../mp.config.js'
import { uuid } from '../../utils'
import { WebView } from '../webview/webview'
import sysapi from '../sysapi'

//通信桥
export class Bridge {
    constructor(opts) {
		this.id = `bridge_${uuid()}`;
        //保存参数信息
		this.opts = opts;
		this.webview = null;
        //逻辑线程
		this.jscore=opts.jscore;
        //parent就是小程序容器miniAppSandbox类
		this.parent=null;
        this.status=0;//状态
        //监听接收logic层发送的消息
		this.jscore.addEventListener('message', this.jscoreMessageHandler.bind(this));

    }
    //接收logic层发送的消息
    jscoreMessageHandler(msg){
        console.log("接收logic层发送的消息:",msg);
        const {type,body}=msg;
        //判断消息是否是发送给当前bridge
        if(body.bridgeId!==this.id){
            return false;
        }

        switch(type){
            case 'logicResourceLoaded':
                this.status=2;//加加后变为2
                this.createApp();
                break;
            case 'appIsCreated':
                this.status++;
                //通知逻辑线程构建渲染初始化数据
                this.notifyMakeInitialData();
                break;
            case 'initialDataIsReady':
                this.status++;
                //设置初始化数据
                this.setInitialData(msg);
            case 'updateModule':
                this.updateModule(body);
                break;
            case 'showToast':
                this.showToast(body);
                break;

            default:
                console.log("default")
                break;
        }

    }
    start(){

        //通知渲染线程加载资源
        this.webview.postMessage({
            type:'loadResource',
            body:{
                appId:this.opts.appId,
                pagePath:this.opts.pagePath,
                platform:config.platform,
                //如果是在开发者工具中，传当前的项目路径
			    currProjectPath:this.opts.currProjectPath,
            }
        })
        //通知逻辑线程加载资源
        this.jscore.postMessage({
            type:'loadResource',
            body:{
                appId:this.opts.appId,
                bridgeId:this.id,
                pages:this.opts.pages,
                platform:config.platform,
                //如果是在开发者工具中，传当前的项目路径
			    currProjectPath:this.opts.currProjectPath,
            }
        })
        
        //告诉主进程，我已经打开小程序
        window.electron.ipcRenderer.send('open-mini-program');
        window.electron.ipcRenderer.on('get-mini-program-info', (_event, opts) =>{

        });
        //通知逻辑线程窗口信息
        this.jscore.postMessage({
            type:'windowInfo',
            body:{
				windowWidth:this.opts.windowWidth,
				windowHeight:this.opts.windowHeight,
				statusBarHeight:55,//状态栏高度
            }
        })
    }
    async init(){
        this.webview=await this.createWebview();
        //监听接收ui层发送的消息
        this.webview.addEventListener('message', this.uiMessageHandler.bind(this));
    }
    //接收ui层发送的消息
    uiMessageHandler(msg){
        const {type,body}=msg;
        switch(type){
            case 'uiResourcesLoaded':
                this.status++;//加加后变为1
                this.createApp();
                break;
            case 'moduleCreated':
                this.uiInstanceCreated(msg.body);
                break;
            case 'moduleMounted':
                this.uiInstanceMounted(msg.body);
                break;
            case 'pageScroll':
                this.pageScroll(msg.body);
                break;
            case 'trrigerEvent':
                this.trrigerEvent(msg.body);
                break;
            default:
                break;
        }
    }
    createWebview(){
        return new Promise((resolve,reject)=>{
            
            //configInfo页面配置,isRoot首页没有返回按钮
            const webview=new WebView({configInfo:this.opts.configInfo,isRoot:this.opts.isRoot});
            webview.parent=this;
            webview.init(()=>{
                resolve(webview)
                /* webview.postMessage({
                    type:'test_ui',
                    body:{
                        as:'ass'
                    }
                }) */
            });
            this.parent.webviewsContainer.appendChild(webview.el)
        })
    }
    createApp(){
        if(this.status!==2){
            return false;
        }
        //通知逻辑线程
        this.jscore.postMessage({
            type:'createApp',
            body:{
                bridgeId:this.id,
                scene:this.opts.scene,
                pagePath:this.opts.pagePath,
                query:this.opts.query,
            }
        })
    }
    //通知逻辑线程构建渲染初始化数据
    notifyMakeInitialData(){
        //通知逻辑线程
        this.jscore.postMessage({
            type:'makeInitialData',
            body:{
                bridgeId:this.id,
                pagePath:this.opts.pagePath,
            }
        })
    }
    
    //设置初始化数据
    setInitialData(msg){
        const {initialData}=msg.body;
        //通知渲染线程
        this.webview.postMessage({
            type:'setInitialData',
            body:{
                initialData,
                pagePath:this.opts.pagePath,
                bridgeId:this.id,
            }
        })
    }
    updateModule(msg){
        const {id,data}=msg;
        //通知渲染线程
        this.webview.postMessage({
            type:'updateModule',
            body:{
                id,data
            }
        })
    }
    showToast(msg){
        const {params}=msg;
        //通知渲染线程
        this.webview.postMessage({
            type:'showToast',
            body:{
                ...params
            }
        })
    }
    uiInstanceCreated(msg){
        const {id,path}=msg;
        //通知逻辑线程
        this.jscore.postMessage({
            type:'createInstance',
            body:{
                id,
                path,
                bridgeId:this.id,
                query:this.opts.query,
            }
        })
    }
    uiInstanceMounted(msg){
        const {id}=msg;
        //通知逻辑线程
        this.jscore.postMessage({
            type:'moduleMounted',
            body:{
                id,
            }
        })
    }
    pageScroll(msg){
        const {id,scrollTop}=msg;
        //通知逻辑线程
        this.jscore.postMessage({
            type:'pageScroll',
            body:{
                id,
                scrollTop
            }
        })
    }
    trrigerEvent(msg){
        const {id,methodName,param}=msg;
        //通知逻辑线程
        this.jscore.postMessage({
            type:'trrigerEvent',
            body:{
                id,
                methodName,
                param
            }
        });
    }
    appShow(){
        if(this.status<2){
            return false;
        }
        //通知逻辑线程
        this.jscore.postMessage({
            type:'appShow',
            body:{

            }
        })
    }
    appHide(){
        if(this.status<2){
            return false;
        }
        //通知逻辑线程
        this.jscore.postMessage({
            type:'appHide',
            body:{

            }
        })
    }
    
    pageShow(){
        if(this.status<2){
            return false;
        }
        //通知逻辑线程
        this.jscore.postMessage({
            type:'pageShow',
            body:{
                bridgeId:this.id,
            }
        })
    }
    pageHide(){
        if(this.status<2){
            return false;
        }
        //通知逻辑线程
        this.jscore.postMessage({
            type:'pageHide',
            body:{

                bridgeId:this.id,
            }
        })
    }
    destroy(){
        //通知逻辑线程
        this.jscore.postMessage({
            type:'pageUnload',
            body:{
                bridgeId:this.id,
            }
        })
    }
}